/**
 * 集成ext 下拉选择框
 * @author：xuqiang
 * @date：2016-11-03
 */
Ext.namespace("Ext.com.bkfm");
Ext.define('Ext.com.bkfm.combobox', {
	extend:"Ext.form.ComboBox",
	//type分为objPath建模获取或者为sql语句获取
	type: 'objPath',
	//建模对象
	objPath: '',
	//sql语句
	sql: '',
	//条件
	filter: '',
	//判读
	order: '',
	queryMode: 'remote',
	displayField: 'DISPLAYVALUE',
    valueField: 'VALUE',
    editable: false,
    minChars: 1,
    setFilter: function(str){
    	this.filter = str;
    },
    setOrder: function(str){
    	this.order = str;
    },
	initComponent: function(){
		if(this.queryMode == "remote"){
			if(this.type =="objPath"){
				this.initObjPathCombox();
			}else if(this.type == "sql"){
				this.initSqlCombox();
			}else{
				Ext.Msg.alert('系统提示', '创建下拉列表异常，无效的存储参数');
			}
		}
		this.callParent(arguments);
	},
	//初始化objpath方式下拉列表
	initObjPathCombox: function(){
		if(Ext.isEmpty(this.objPath)){
			Ext.Msg.alert('系统提示', '创建下拉列表异常，无效的存储参数');
			return;
		}
		this.store = this.createComboxStore();
	},
	initSqlCombox: function(){
		if(Ext.isEmpty(this.sql)){
			Ext.Msg.alert('系统提示', '创建下拉列表异常，无效的sql参数');
			return;
		}
		this.store = this.createComboxStore();
	},
	//创建store
	createComboxStore: function(){
		var combox = this;
		var filterParam = {

		};
/*		if(this.type =="objPath"){
			filterParam["objPath"] = this.objPath;
			filterParam["filter"] = this.filter;
			filterParam["orderby"] = this.order;
		}else if(this.type =="sql"){
			filterParam["sql"] = encodeURIComponent(this.sql);
		}*/
		var store = Ext.create('Ext.data.Store', {
			singleton : true,
			proxy: {
                type: 'ajax',
                url: CONTEXT.contextPath+"/bkfm/metadata/v1/getcombobox",
                actionMethods : 'post',
                reader: {
                    type: 'json',
                    root: 'list'
                }
	        },
            baseParams:filterParam,
            listeners : {
				beforeload : function(store,operation,eOpts ) {
					if(combox.type =="objPath"){
						filterParam["obj_path"] = combox.objPath;
						filterParam["filter"] = combox.filter;
						filterParam["orderby"] = combox.order;
					}else if(combox.type =="sql"){
						filterParam["sql"] = encodeURIComponent(combox.sql);
					}
					//在下拉框可以编辑的情况下，动态根据输入的值模糊匹配对应的选择项
					if(!Ext.isEmpty(operation.params)){
						if(!Ext.isEmpty(operation.params.query)){
							if(!Ext.isEmpty(filterParam["filter"])){
								filterParam["filter"] = filterParam["filter"] + " AND DISPLAYVALUE LIKE '%"+operation.params.query+"%'";
							}else{
								filterParam["filter"] = " DISPLAYVALUE LIKE '%"+operation.params.query+"%'";
							}
						}
					}
					this.baseParams = filterParam;

					Ext.apply(store.proxy.extraParams, this.baseParams);
				}
            },
		    fields: ['VALUE', 'DISPLAYVALUE']
		});

		return store;
	}
	/**
	 * 给下啦框添加值
	 * 这里鼻息使用record的方式添加，如果单独使用value的方式会是的下拉框的value和rawvalue值相同
	 * demo:{
	 * 	VALUE: '123',
	 *  DISPLAYVALUE: 'DEMO'
	 * }
	 */
	,fillValue: function(record){
		Ext.define('R', {
		    extend: 'Ext.data.Model',
		    fields: [
		        {name: 'VALUE'},
		        {name: 'DISPLAYVALUE'}
		    ]
		});
		this.setValue(Ext.create('R',record));
	}
    ,setValue: function(value, doSelect) {
        var me = this,
            valueNotFoundText = me.valueNotFoundText,
            inputEl = me.inputEl,
            i, len, record,
            dataObj,
            matchedRecords = [],
            displayTplData = [],
            processedValue = [];

        if (me.store !=null && me.store.loading) {
            // Called while the Store is loading. Ensure it is processed by the onLoad method.
            me.value = value;
            me.setHiddenValue(me.value);
            return me;
        }

        // This method processes multi-values, so ensure value is an array.
        value = Ext.Array.from(value);

        // Loop through values, matching each from the Store, and collecting matched records
        for (i = 0, len = value.length; i < len; i++) {
            record = value[i];
            if (!record || !record.isModel) {
                record = me.findRecordByValue(record);
            }
            // record found, select it.
            if (record) {
                matchedRecords.push(record);
                displayTplData.push(record.data);
                processedValue.push(record.get(me.valueField));
            }
            // record was not found, this could happen because
            // store is not loaded or they set a value not in the store
            else {
                // If we are allowing insertion of values not represented in the Store, then push the value and
                // create a fake record data object to push as a display value for use by the displayTpl
                if (!me.forceSelection) {
                    processedValue.push(value[i]);
                    dataObj = {};
                    dataObj[me.displayField] = value[i];
                    displayTplData.push(dataObj);
                    // TODO: Add config to create new records on selection of a value that has no match in the Store
                }
                // Else, if valueNotFoundText is defined, display it, otherwise display nothing for this value
                else if (Ext.isDefined(valueNotFoundText)) {
                    displayTplData.push(valueNotFoundText);
                }
            }
        }

        // Set the value of this field. If we are multiselecting, then that is an array.
        me.setHiddenValue(processedValue);
        me.value = me.multiSelect ? processedValue : processedValue[0];
        if (!Ext.isDefined(me.value)) {
            me.value = null;
        }
        me.displayTplData = displayTplData; //store for getDisplayValue method
        me.lastSelection = me.valueModels = matchedRecords;

        if (inputEl && me.emptyText && !Ext.isEmpty(value)) {
            inputEl.removeCls(me.emptyCls);
        }

        // Calculate raw value from the collection of Model data
        me.setRawValue(me.getDisplayValue());
        me.checkChange();

        if (doSelect !== false) {
            me.syncSelection();
        }
        me.applyEmptyText();

        return me;
    },
    /**
     * @private Synchronizes the selection in the picker to match the current value of the combobox.
     */
    syncSelection: function() {
    	//debugger;
        var me = this,
            picker = me.picker,
            selection, selModel,
            values = me.valueModels || [],
            vLen  = values.length, v, value;

        if (picker) {
            // From the value, find the Models that are in the store's current data
            selection = [];
            for (v = 0; v < vLen; v++) {
                value = values[v];

                if (value && value.isModel && me.store && me.store.indexOf(value) >= 0) {
                    selection.push(value);
                }
            }

            // Update the selection to match
            me.ignoreSelection++;
            selModel = picker.getSelectionModel();
            selModel.deselectAll();
            if (selection.length) {
                selModel.select(selection, undefined, true);
            }
            me.ignoreSelection--;
        }
    }
    /**
     * 获取注册组件类型
     */
    ,getXType:function(){
    	return "select"
    }

});